<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    hostname: new URL('http://yoursite.com').hostname,
    root: '/',
    scheme: 'Pisces',
    version: '7.6.0',
    exturl: false,
    sidebar: {"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},
    copycode: {"enable":false,"show_result":false,"style":null},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":false},
    bookmark: {"enable":false,"color":"#222","save":"auto"},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    comments: {"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    path: '',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}
  };
</script>

  <meta name="description" content="instruction set architecture, or ISAvirtual addressthe programe counter virtual address and programe counter register file contain 16 named locations storing 64-bit values.These registers can hold add">
<meta property="og:type" content="article">
<meta property="og:title" content="csapp">
<meta property="og:url" content="http://yoursite.com/2022/01/02/csapp/index.html">
<meta property="og:site_name" content="SRCNN">
<meta property="og:description" content="instruction set architecture, or ISAvirtual addressthe programe counter virtual address and programe counter register file contain 16 named locations storing 64-bit values.These registers can hold add">
<meta property="og:locale" content="en_US">
<meta property="article:published_time" content="2022-01-02T03:03:44.000Z">
<meta property="article:modified_time" content="2022-01-16T08:11:49.907Z">
<meta property="article:author" content="Z.J. Jiang">
<meta property="article:tag" content="SISR">
<meta property="article:tag" content=" FH">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://yoursite.com/2022/01/02/csapp/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true
  };
</script>

  <title>csapp | SRCNN</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-meta">

    <div>
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">SRCNN</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <p class="site-subtitle">SISR-FH</p>
  </div>

  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>Home</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>Tags</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-fw fa-th"></i>Categories</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>Archives</a>

  </li>
  </ul>

</nav>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content">
            

  <div class="posts-expand">
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block " lang="en">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2022/01/02/csapp/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="Z.J. Jiang">
      <meta itemprop="description" content="about the single image super-resolution and face hallucination">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="SRCNN">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          csapp
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">Posted on</span>

              <time title="Created: 2022-01-02 11:03:44" itemprop="dateCreated datePublished" datetime="2022-01-02T11:03:44+08:00">2022-01-02</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">Edited on</span>
                <time title="Modified: 2022-01-16 16:11:49" itemprop="dateModified" datetime="2022-01-16T16:11:49+08:00">2022-01-16</time>
              </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>instruction set architecture, or ISA<br>virtual address<br>the programe counter</p>
<p>virtual address and programe counter</p>
<p>register file contain 16 named locations storing 64-bit values.<br>These registers can hold addresses(corresponding to C pointer) // 保存的是地址。！！！！不管什么，保存的都是地址。。。<br>The condition code registers hold status informatino about the most recently executed arithemetci or logical instruction. These are used to implement condition</p>
<p>A set of vector resiters can each hold one or more integer or floating-point values</p>
<p>Even for scalar data types, assembly code makes no distinctions between signed or unsigned integers, between different types of pointers, or even between pointers and integers.</p>
<p>A key lesson to learn from this is that the program executed by the machine is simply a sequence of bytes encoding a series of instructions.</p>
<p>16bits: word<br>32bits: double words<br>64bits: quad words</p>
<p>16 general-purpose register storing 64-bit values. These registers are used to store integer data as well as pointers.</p>
<p>operand specifiers<br>操作数 most instruction have one or more operands specifying the source values to use in performing an operation and the destinaton location into which to place the result.</p>
<p>This technique takes advantage of the property that an instruction generating a 4-byte value with a register as the destination will fill the upper 4 bytes with zeros.</p>
<p>mismatch between instruction suffix and register ID</p>
<p>By way of background, a stack is a data structure whre values can be added or deleted, but only according to a “last-in, first-out” discipline.</p>
<p>operations are divided into four groups: load effective address, unary, binary, and shifts</p>
<ul>
<li>lea</li>
<li>unary 一元</li>
<li>binary 二元</li>
<li>shifts 移位</li>
</ul>
<p>leaq: instead of reading from the designated location, the instruction copies the effective address to the destination.</p>
<p>Note that when the second operand is a memory location, the processor must read the value from memory, perform the operation, and then write the result back to memory</p>
<p>CF (unsigned) t &lt; (unsigned) a Unsigned overflow<br>ZF (t == 0) Zero<br>SF (t &lt; 0) Negetive<br>OF (a &lt; 0 == b &lt; 0) &amp;&amp; (t &lt; 0 != a &lt; 0) Signed overflow</p>
<p>use contion code<br>1、we can set a single byte to 0 or 1 depending on some combination of the condition codes<br>2、we can conditionally jump to some other part of the progrma<br>3、we can conditionally transfer data.</p>
<p>In generating the object-code file, the assembler determines the addresses of all labeled instructions and encodes the jump targets (the addresses of the destination instructions) as part of the jump instructions.</p>
<p>not that jump instruction, but the next instruction of jump</p>
<p>Implementing Conditional Branches with Conditional Moves</p>
<p>why code based on conditional data transfers can outperform code based on conditional control transfers?</p>
<p>processors achieve high performance though pipelining,  — branch prediction logic</p>
<p>such a misprediction can incur a serious penalty,say,15-30clock cycles of wasted effort, causing a serious degradation of program performance</p>
<p>combination of conditional tests and jumps are used to implement the effect of loops.</p>
<p>switch allow an efficient implementation using a data structure called a jump table.</p>
<p>use of a jump table allows a very efficient way to implement a multiway branch</p>
<p>procedure involve:</p>
<ol>
<li>Passing control</li>
<li>Passing data.</li>
<li>Allocating and deallocating memory</li>
</ol>
<p>3.7.4 接下来应该读 Local Storage on the Stack</p>
<p>static:link</p>
<ol>
<li>找到符号。f 定位每一个函数f，能够定位到全局变量</li>
<li>symbol resolution</li>
<li>relocate</li>
</ol>
<p>文件elf<br>读头，寻道<br>连续的0/1串，起来就是</p>
<p>本质上就是视角上的不同。</p>
<ul>
<li><p>offset n<br>bytes</p>
</li>
<li><p>offset </p>
</li>
</ul>
<ul>
<li>offset 0</li>
</ul>
<ol>
<li>disk address 即 offset 0 但是无法读到大小？</li>
</ol>
<p>ELF : magic number</p>
<p>0-&gt; header -&gt; section header table</p>
<p>大家好，今天主要讨论静态链接。我将会从符号定位、符号解析、以及重定位三个方面来介绍静态链接。符号定位主要讨论的是Linux如何利用ELF文件格式来定位函数和全局变量。符号解析主要讨论多个可重定位文件链接到一起时如何解析符号，遇到多重定义符号怎么处理等内容。重定位，主要讨论多个可重定位文件链接成可执行程序时如何修正全局变量和函数调用的调用地址。OK，废话不多说。那我们就开始吧。</p>
<p>我们将会使用这个例子，贯穿整个静态链接的介绍。这个例子很简单，从csapp这本书摘抄出来的。首先有一个sum函数，计算一个数组的和。有一个全局的array数组，里面有1和2两个数据。一个main函数，调用sum函数，计算array数组的和。我们将这个文件进行预处理，编译，汇编最终生成了一个main.o的文件。在计算机中，一个文件其实就是字节序列，就是一些01串而已。那么如何从main.o这个01串中定位到array符号的呢？array中包含的数据到底是怎么存放在main.o这个文件中呢？</p>
<p>在Linux中像main.o这种目标文件是被组织成一种特殊的格式，叫做<br>Executabl 可执行<br>Linkable 可链接<br>Format 格式<br>简称ELF格式。<br>这张图就展现了一个elf文件格式的基本结构。<br>最开始的offset 0就是这个文件开始的地方。文件开始有一个elf header。之后还有一些.text 段.data 段等。最后还有一个Section header table，就叫做节头表吧。它是描述.text .data节的。这张图已经给了ELF文件大概的全景图，接下来会分别介绍其中的细节。首先介绍一个ELF Header。只有解析了elf header之后，才能根据其中的内容解析elf文件的其他部分。<br>(hexdump -C main.o 看一下整体的预览。)<br>对于ELF，首部的信息包括文件类型、机器类型等信息。在Linux读取ELF文件时，Linux将ELF Header从Byte翻译成内存中的数据结构：这个结构体就像这张PPT展示的一样。通常一个elf header中会存放这么些个东西，这个结构体是从/usr/bin/elf.h摘抄出来的。<br>每个项目列出来讲一讲。<br>e_indent<br>e_type<br>e_machine<br>e_version<br>e_entry<br>e_phoff<br>e_shoff<br>e_flags<br>e_ehsize<br>e_phentsize<br>e_phnum<br>e_shentsize<br>e_shnum<br>e_shstrndx<br>我们需要重点关注的是e_shoff, e_ensize e_shentsize e_shnum 变量。<br>// 应该需要吧elf.h 和hexdump之后的文件放上去。对照着讲。结合着讲。<br>起始位置的16个字节为magic number，在这之后偏移2+2+4+8+8=24个字节之后，为e_shoff，是section header table 的偏移量。数值为0x280 = 640，在这之后，对e_shoff偏移4字节是e_ehsize=0x40 表示elf header 的长度，即64个字节。我们可以看到整个elf_header 是64个字节，算得非常准确。最后是e_shnum = 0x0d = 13个section，字符串表的索引是12.好了我们，已经人眼识别，将整个elf header解析出来，接下来，我们用一个readelf工具，直接将header解析出来。</p>
<p>使用readelf -h main.o就可以将main.o的elf header解析出来了。划线的地方是需要重点关注的地方。使用readelf工具我们就可以更清楚的看到，section header table的偏移量，elf文件头的大小，每一个section header table的entry 大小。一个有多少个section header table。</p>
<p>OK，根据目前我们解析得到的内容，可以画出一个elf文件现在大概这样的。首先，有64Bytes的ELF header。在header中，根据e_shoff可以找到SHT的位置。根据e_shentnum我们可以知道一个有多少个SHT有多少个表项。根据e_shentsize可以知道SHT每个表项的大小。至此，我们可以计算出整个elf文件的大小。<br>e_shoff + e_shentnum * e_shentsize = 1472字节。</p>
<p>接下来把目光放到section header table中。这个结构体就是描述section header table的。<br>SHT描述了ELF中不同的节，包括数据节、代码节等。这些Section中的数据是由编译器生成的，按照section的组织写入到磁盘上的ELF文件中。SHT的每一项都可以被数据结构ELF64_Shdr所描述。<br>列出来，讲一讲。<br>其中包含，<br>sh_name 它是string table的index<br>sh_type: section type:<br>sh_flags: section flasg</p>
<p>// 需要结合代码展示一个hexdump的结构。</p>
<p>接下来我们就和解析ELF Header一样来人眼解析一个这个结构体。和解析ELF Header一样，对于SHT的每一个表项，按照上一页提到的数据结构逐个Byte解析，我们就可以得到.text对ELF文件的偏移：.sh_offset = 0x00000000040。回忆起我们先前得知ELF header的大小就是0x40，也即64Bytes，因此.text所处的位置正是Header之后。并且，它的大小为.sh_size - 0x0000000024</p>
<p>同样的，我们可以使用readelf作弊一下，可以将所有的section header table列出来。<br>值得一提的是，SHT中总存在[0]项目，它被视为未定义的符号所在Section，SHN_UNDEF，也就是0.</p>
<p>OK，现在elf header和section header table已经解析完毕了，大概可以画出这么一张图。<br>首先解析，elf_header, 我们得到section header table的位置，解析section header table之后我们可以得到各个section 在文件中的位置，以及它的大小。</p>
<p>解析来我们把目光放在.symbol section中。关于什么是符号的问题。<br>由模块m定义并能被其他模块引用的全局符号。<br>由其他模块定义并被模块m引用的全局符号。<br>只被模块m定义和引用的局部符号。</p>
<p>类似elf header 和 section header table。符号表也是由一个结构体来描述的。<br>st_name: 符号的名字，它是字符串表的索引。<br>st_info: 高四位是bind信息，低四位是type信息。<br>st_other: 保留信息<br>st_shndx: 该符号保存在某个section的index<br>st_value: 保存在某个section的offset<br>st_size: 符号的大小。</p>
<p>符号的绑定类型主要有：<br>STB_LOCAL<br>STB_GLOBAL<br>STB_WEAK</p>
<p>符号的type主要有：<br>NOTYPE<br>OBJECT<br>FUNC</p>
<p>同样的我们可以肉眼解析一个符号。例如，开头提到的array<br>st_name 是0x08，在字符串表偏移8个字节的位置，<br>bind是1： 为STB_GLOBAL<br>type是1：为STT_OBJECT<br>st_shndx: 是3 说明这个符号存储在.data节<br>st_value是0，说明array在.data节开始的位置。<br>st_size是0x08, 说明array符号大小为8个字节。</p>
<p>自此，我们可以知道array符号在elf文件位置的计算公式：<br>start：.data节在elf文件的偏移量+st_value<br>end: start+st_size<br>最终我们找到了array符号的存储位置。</p>
<p>同样的，也可以使用readelf工具作弊一下，使用readelf -s 命令就可以将符号表的信息列举出来。</p>
<p>首先解析，elf_header, 我们得到section header table的位置，解析section header table<br>我们可以得到.symtab的位置，解析.symtab就可以得到各个符号在文件中的存储位置。自此，终于可以成功定位符号了。因而我们解决了开头提到的符号定位问题。</p>
<p>接下来介绍符号解析问题。</p>
<p>如何design file？？？？ 疯狂搞链接，套娃。。。。之类的。很像MP4文件格式，<br>所有的文件格式都是按照树，按照图去组织的。</p>
<p>external intenal层</p>
<p>如何知道符号表在文件中的哪一个位置。</p>

    </div>

    
    
    

      <footer class="post-footer">

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2021/10/20/platform%E8%AE%BE%E5%A4%87%E9%A9%B1%E5%8A%A8/" rel="prev" title="platform设备驱动">
      <i class="fa fa-chevron-left"></i> platform设备驱动
    </a></div>
      <div class="post-nav-item">
    <a href="/2022/03/06/STM32/" rel="next" title="STM32">
      STM32 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  

  </div>


          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let activeClass = CONFIG.comments.activeClass;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">Z.J. Jiang</p>
  <div class="site-description" itemprop="description">about the single image super-resolution and face hallucination</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">42</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">11</span>
        <span class="site-state-item-name">categories</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">1</span>
        <span class="site-state-item-name">tags</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/jzijin" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;jzijin" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="/atom.xml" title="RSS → &#x2F;atom.xml"><i class="fa fa-fw fa-rss"></i>RSS</a>
      </span>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title">
      <i class="fa fa-fw fa-link"></i>
      Links
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="http://www.njust.edu.cn/" title="http:&#x2F;&#x2F;www.njust.edu.cn" rel="noopener" target="_blank">南京理工大学</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="http://ehall.njust.edu.cn/new/index.html" title="http:&#x2F;&#x2F;ehall.njust.edu.cn&#x2F;new&#x2F;index.html" rel="noopener" target="_blank">南京理工大学智慧服务</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="http://lib.njust.edu.cn/" title="http:&#x2F;&#x2F;lib.njust.edu.cn&#x2F;" rel="noopener" target="_blank">南京理工大学图书馆</a>
        </li>
    </ul>
  </div>

      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Z.J. Jiang</span>
</div>
  <div class="powered-by">Powered by <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> v4.2.0
  </div>
  <span class="post-meta-divider">|</span>
  <div class="theme-info">Theme – <a href="https://pisces.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Pisces</a> v7.6.0
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

  

</body>
</html>
